<template>
	<div>
		<!--面包屑-->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }"> 首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>分类参数</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图 -->
		<el-card>
			<!-- 注意提示 -->
			<el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"> </el-alert>
			<el-row class="cat_opt">
				<el-col>
					<span>选择商品分类：</span>
					<!-- Cascader 级联选择器 -->
					<el-cascader v-model="selectvalue" :options="catelist" :props="cateListProps" @change="handleChange"></el-cascader>
				</el-col>
			</el-row>

			<!-- tab栏目切换 -->
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="动态参数" name="many">
					<el-button type="primary" :disabled="isBtnDisabled" @click="titleDialogVisible = true">添加参数</el-button>
					<!--动态表格-->
					<el-table :data="manyTableData" border stripe>
						<el-table-column type="expand">
							<template slot-scope="scoped">
								<!--tag标签-->
								<el-tag @close="handelClose(index, scoped.row)" closable v-for="(item, index) in scoped.row.attr_vals" :key="index">
									{{ item }}
								</el-tag>
								<!--新增tag标签-->
								<el-input
									class="input-new-tag"
									v-if="scoped.row.inputVisible"
									v-model="scoped.row.inputTagValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scoped.row)"
									@blur="handleInputConfirm(scoped.row)"
								>
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index" label="#"></el-table-column>
						<el-table-column prop="attr_name" label="参数名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scoped">
								<el-button type="primary" icon="el-icon-edit" @click="editData(scoped.row)">编辑</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="deleteData(scoped.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="静态属性" name="only">
					<el-button type="primary" :disabled="isBtnDisabled" @click="titleDialogVisible = true">添加属性</el-button>

					<!--静态表格-->
					<el-table :data="onlyTableData" border stripe>
						<el-table-column type="expand">
							<template slot-scope="scoped">
								<!--tag标签-->
								<el-tag @close="handelClose(index, scoped.row)" closable v-for="(item, index) in scoped.row.attr_vals" :key="index">
									{{ item }}
								</el-tag>
								<!--新增tag标签-->
								<el-input
									class="input-new-tag"
									v-if="scoped.row.inputVisible"
									v-model="scoped.row.inputTagValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scoped.row)"
									@blur="handleInputConfirm(scoped.row)"
								>
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index" label="#"></el-table-column>
						<el-table-column prop="attr_name" label="属性名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scoped">
								<el-button type="primary" icon="el-icon-edit" @click="editData(scoped.row)">编辑</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="deleteData(scoped.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<!--添加动态/静态参数对话框-->
		<el-dialog :title="'添加' + titleText" :visible.sync="titleDialogVisible" width="30%" @close="DialogClose">
			<!--form表单-->
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="addForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="titleDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addParams">确 定</el-button>
			</span>
		</el-dialog>

		<!--修改动态/静态参数对话框-->
		<el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="30%">
			<!--form表单-->
			<el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input v-model="editForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editParams">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	data() {
		return {
			// 分类数据
			catelist: [],
			// tab栏目当前栏目
			activeName: 'many',
			// props配置
			cateListProps: {
				expandTrigger: 'hover',
				value: 'cat_id',
				label: 'cat_name',
				children: 'children',
			},
			// 选中ID,存储在此处
			selectvalue: [],
			// 获取到的动态数据
			manyTableData: [],
			// 获取到的静态数据
			onlyTableData: [],
			// 控制添加参数/属性对话框显示与隐藏的属性
			titleDialogVisible: false,
			// form表单添加的内容
			addForm: {
				attr_name: '',
			},
			// form表单添加的规则
			addFormRules: {
				attr_name: [
					{ required: true, message: '请输入参数名称', trigger: 'blur' },
					{ min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
				],
			},
			// form表单修改编辑的内容
			editDialogVisible: false,
			editForm: {
				attr_Id: '',
				attr_name: '',
			},
		}
	},

	created() {
		this.getCateList()
	},
	methods: {
		async getCateList() {
			const { data: res } = await this.$http.get('categories')
			if (res.meta.status !== 200) {
				this.$message.error('获取分类数据失败')
			}
			this.catelist = res.data
			// console.log(this.catelist)
		},
		// tab栏切换事件
		handleClick() {
			this.getParamsData()
		},
		// 级联选择框，发生变化，触发此事件
		handleChange() {
			this.getParamsData()
		},

		// 获取参数的列表数据
		async getParamsData() {
			if (this.selectvalue.length !== 3) {
				this.selectvalue = []
				this.manyTableData = []
				this.onlyTableData = []
				return
			}
			const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
			if (res.meta.status !== 200) {
				return this.$message.error('获取参数失败')
			}
			if (this.activeName === 'many') {
				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
					item.inputVisible = false
					item.inputTagValue = ''
				})
				this.manyTableData = res.data
			} else {
				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
					item.inputVisible = false
					item.inputTagValue = ''
				})
				this.onlyTableData = res.data
			}
		},
		// 监听添加对话框的关闭事件
		DialogClose() {
			this.$refs.addFormRef.resetFields()
		},

		// 添加参数/属性提交请求
		addParams() {
			this.$refs.addFormRef.validate(async valid => {
				if (!valid) return
				const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
					attr_name: this.addForm.attr_name,
					attr_sel: this.activeName,
				})

				if (res.meta.status !== 201) {
					return this.$message.error('添加失败')
				}
				await this.getParamsData()
				this.titleDialogVisible = false
				this.$message.success('添加成功')
			})
		},

		// 打开编辑对话框
		editData(info) {
			this.editDialogVisible = true
			this.editForm.attr_name = info.attr_name
			this.editForm.attr_Id = info.attr_id
		},
		// 修改参数/属性提交请求
		async editParams() {
			const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_Id}`, {
				attr_name: this.editForm.attr_name,
				attr_sel: this.activeName,
			})
			if (res.meta.status !== 200) {
				return this.$message.error('修改失败')
			}
			await this.getParamsData()
			this.$message.success('修改成功')
			this.editDialogVisible = false
		},

		// 删除参数
		deleteData(info) {
			this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${info.attr_id}`)
					if (res.meta.status !== 200) {
						return this.$message.error('删除失败')
					}
					await this.getParamsData()

					this.$message({
						type: 'success',
						message: '删除成功!',
					})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除',
					})
				})
		},

		// TODO  发起ajax请求,保存attr_vals可选性到数据库（不管添加还是删除，都会用到这个）
		async saveAttrVals(info) {
			const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${info.attr_id}`, {
				attr_name: info.attr_name,
				attr_sel: info.attr_sel,
				attr_vals: info.attr_vals.join(' '),
			})
			if (res.meta.status !== 200) {
				return this.$message.error('操作失败')
			}
			// this.$message.success('添加成功')
			info.inputVisible = false
			info.inputTagValue = ''
		},

		// TODO 添加对应的参数可选项
		handleInputConfirm(info) {
			if (info.inputTagValue.trim().length === 0) {
				info.inputTagValue = ''
				info.inputVisible = false
				return
			}
			// 每次添加新参数，都是推到attr_vals以数组形式保存
			// 当发起请求时，再转换成字符串
			info.attr_vals.push(info.inputTagValue)
			this.saveAttrVals(info)
		},

		// TODO 删除对应的参数可选项
		handelClose(index, info) {
			info.attr_vals.splice(index, 1)
			// console.log(info)
			this.saveAttrVals(info)
		},

		// tag input触发的事件(点击按钮时)
		showInput(info) {
			info.inputVisible = true
			this.$nextTick(_ => {
				this.$refs.saveTagInput.$refs.input.focus()
				// 无用
				console.log(_)
			})
		},
	},
	// 计算属性
	computed: {
		isBtnDisabled() {
			if (this.selectvalue.length !== 3) {
				return true
			} else {
				return false
			}
		},
		cateId() {
			if (this.selectvalue.length === 3) {
				return this.selectvalue[2]
			}
		},
		titleText() {
			if (this.activeName === 'many') {
				return '动态参数'
			} else {
				return '静态属性'
			}
		},
	},
}
</script>

<style lang="less" scoped>
.cat_opt {
	margin: 15px 0;
}
.el-tag {
	margin: 0 5px;
}

.input-new-tag {
	width: 90px;
	margin-left: 10px;
	vertical-align: bottom;
}

.button-new-tag {
	margin-left: 10px;
	height: 32px;
	line-height: 30px;
	padding-top: 0;
	padding-bottom: 0;
}
</style>
